<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 图片上传
 *
 * @author      Eden
 * @datetime    2016/11/30 23:32
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Images_Model extends API_Model
{
    private $field = 'file';
    private $width = 0;
    private $height = 0;
    private $count = 0;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {

            if ($this->input->method(true) !== 'POST') {
                $send['error'] = '非法请求';
                break;
            }

            if (empty($_FILES)) {
                $send['error'] = '没有图片被上传';
                break;
            }

            // 如果设置了宽度
            if (isset($params['width']) && isset($params['height'])) {
                $width = intval($params['width']);
                $height = intval($params['height']);
                if (!empty($width) && !empty($height)) {
                    $this->width = $width;
                    $this->height = $height;
                }
            }

            $success = [];
            $failed = 0;
            $this->count = count($_FILES);
            foreach($_FILES as $k => $f) {
                $res = local($f);
                if (!$res) {
                    $failed++;
                } else {
                    $success[$k] = $res;
                }
            }

            $return = array();
            foreach ($success as $key => $succ) {
                $return[] = array(
                    'key' => value($succ, 'key'),
                    'view' => [
                        'thumbPath' => thumb($succ['key'], $this->width, $this->height),
                        'fullPath' => thumb($succ['key'])
                    ]
                );
            }

            $successCount = count($success);
            $send['state'] = true;
            $send['data'] = array(
                'total' => $this->count,
                'successNum' => $successCount,
                'failedNum' => $this->count - $successCount,
                'successData' => $return,
            );
        } while(false);

        $this->output->send($send);
    }
}
